<template>
  <v-chart class="chart" :option="option" autoresize />
</template>

<script setup>
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { ScatterChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent, VisualMapComponent } from 'echarts/components';
import VChart, { THEME_KEY } from 'vue-echarts';
import { ref, provide } from 'vue';

// 注册 ECharts 组件
use([
  CanvasRenderer,
  ScatterChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  VisualMapComponent,
]);

provide(THEME_KEY, 'light');

const props = defineProps({
  chartData: {
    type: Object,
    required: true,
  },
});

const option = ref({
  legend: {
    data: ['新能源', '内燃车'],
    left: 'center',
  },
  grid: {
    left: '5%',
    right: '5%',
    bottom: '10%',
    top: '10%',
    containLabel: true,
  },
  xAxis: {
    type: 'value',
    name: '价格(USD)',
    nameLocation: 'middle',
    nameGap: 30,
    splitLine: {
      lineStyle: {
        type: 'dashed',
        color: '#eee'
      },
    },
    axisLabel: {
      formatter: '{value}',
    },
  },
  yAxis: {
    type: 'value',
    name: '续航里程(km)',
    nameLocation: 'middle',
    nameGap: 40,
    splitLine: {
      lineStyle: {
        type: 'dashed',
        color: '#eee'
      },
    },
    axisLabel: {
      formatter: function (value) {
        // 将0值格式化为NA
        return value === 0 ? 'NA' : value;
      }
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: function (params) {
      const data = params.data;
      const range = data[1] === 0 ? 'NA' : `${data[1]} km`;
      return `${data[3]}<br/>价格: ${data[0].toLocaleString()} USD<br/>续航: ${range}`;
    }
  },
  series: [
    {
      name: '新能源',
      data: props.chartData.newEnergyData,
      type: 'scatter',
      symbolSize: function (data) {
        // 第三个值为销量代理值，乘以一个系数作为气泡大小
        return data[2] * 1.5;
      },
      itemStyle: {
        color: '#5470c6',
        opacity: 0.7
      }
    },
    {
      name: '内燃车',
      data: props.chartData.iceData,
      type: 'scatter',
      symbolSize: function (data) {
        return data[2] * 1.5;
      },
      itemStyle: {
        color: '#91cc75',
        opacity: 0.7
      }
    }
  ]
});
</script>

<style scoped>
.chart {
  height: 450px;
  width: 100%;
}
</style>